<script lang="ts" setup>
import type {
  OnActionClickParams,
  VxeTableGridOptions,
} from '#/adapter/vxe-table';
import type { SystemDeptApi } from '#/api/system/dept';

import { ref } from 'vue';

import { Page, useVbenModal } from '@vben/common-ui';

import { ElButton, ElLoading, ElMessage, ElMessageBox } from 'element-plus';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { deleteDept, getDeptList } from '#/api/system/dept';
import { $t } from '#/locales';

import { useColumns } from './data';
import Form from './modules/form.vue';

const [FormModal, formModalApi] = useVbenModal({
  connectedComponent: Form,
  destroyOnClose: true,
});
/**
 * 表格操作按钮的回调函数
 */
function onActionClick({
  code,
  row,
}: OnActionClickParams<SystemDeptApi.SystemDept>) {
  switch (code) {
    case 'append': {
      onAppend(row);
      break;
    }
    case 'delete': {
      onDelete(row);
      break;
    }
    case 'edit': {
      onEdit(row);
      break;
    }
  }
}
/**
 * 删除部门
 * @param row
 */
function onDelete(row: SystemDeptApi.SystemDept) {
  ElMessageBox.confirm(`确定删除【${row.deptName}】吗`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      const loadingInstance = ElLoading.service({
        lock: true,
        text: $t('ui.actionMessage.deleting', [row.name]),
        spinner: 'el-icon-loading', // 使用内置图标名
        background: 'rgba(0, 0, 0, 0.7)',
      });
      deleteDept(row.deptId)
        .then(() => {
          ElMessage.success($t('ui.actionMessage.deleteSuccess', [row.name]));
          refreshGrid();
        })
        .finally(() => {
          loadingInstance.close();
        });
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: 'Delete canceled',
      });
    });
}
/**
 * 刷新表格
 */
function refreshGrid() {
  gridApi.query();
}
/**
 * 编辑部门
 * @param row
 */
function onEdit(row: SystemDeptApi.SystemDept) {
  formModalApi.setData(row).open();
}

/**
 * 添加下级部门
 * @param row
 */
function onAppend(row: SystemDeptApi.SystemDept) {
  formModalApi.setData({ parentId: row.deptId }).open();
}

/**
 * 创建新部门
 */
function onCreate() {
  formModalApi.setData({ parentId: 0 }).open();
}
const [Grid, gridApi] = useVbenVxeGrid({
  gridEvents: {},
  gridOptions: {
    columns: useColumns(onActionClick),
    height: 'auto',
    keepSource: true,
    pagerConfig: {
      enabled: false,
    },
    proxyConfig: {
      ajax: {
        query: async (_params) => {
          return await getDeptList();
        },
      },
    },
    toolbarConfig: {
      custom: true,
      export: false,
      refresh: { code: 'query' },
      zoom: true,
    },
    treeConfig: {
      parentField: 'parentId',
      rowField: 'deptId',
      transform: false,
    },
  } as VxeTableGridOptions,
});
const isExpanded = ref(false);

// 折叠全部 /展开全部
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
  gridApi.grid?.setAllTreeExpand(isExpanded.value);
};
</script>

<template>
  <Page auto-content-height>
    <FormModal @success="refreshGrid" />
    <Grid table-title="部门列表">
      <template #toolbar-actions></template>
      <template #toolbar-tools>
        <ElButton type="primary" @click="onCreate"> 新建部门 </ElButton>
        <ElButton class="mr-2" type="primary" @click="toggleExpand">
          {{ isExpanded ? '折叠全部' : '展开全部' }}
        </ElButton>
      </template>
    </Grid>
  </Page>
</template>
